package com.gxa.modules.pc.sys.usermanager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxa.common.utils.*;
import com.gxa.modules.pc.sys.usermanager.dto.RolePcDto;
import com.gxa.modules.pc.sys.usermanager.dto.UserPcDto;
import com.gxa.modules.pc.sys.usermanager.dto.UserSearchDto;
import com.gxa.modules.pc.sys.usermanager.mapper.UserPcMapper;
import com.gxa.modules.pc.sys.usermanager.service.UserPcService;
import com.gxa.modules.sys.entity.User;
import com.gxa.modules.sys.mapper.UserMapper;
import com.gxa.modules.sys.mapper.UserRoleMapper;
import com.gxa.modules.sys.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author zhuiyi
 * @since 2022-10-29 04:01:04
 */
@Slf4j
@Service
public class UserPcServiceImpl implements UserPcService {

    @Autowired
    private UserPcMapper userPcMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public Result list(UserSearchDto userSearchDto) {
        Integer pageNum = userSearchDto.getPageNum();
        Integer pageSize = userSearchDto.getPageSize();
        Integer pageNum1 = (pageNum-1)*pageSize;
        userSearchDto.setPageNum(pageNum1);
        Integer count = userPcMapper.count(userSearchDto);
        List<UserPcDto> userPcDtos = userPcMapper.queryAll(userSearchDto);
        PageUtils pageUtils = new PageUtils(userPcDtos, count, pageSize, pageNum);
        return new Result().ok(pageUtils);
    }

    @Override
    public void add(UserPcDto userPcDto, Integer roleId) {
        String encryptpwd = MD5Utils.encrypt(userPcDto.getUserName(), userPcDto.getUserPassword());
        userPcDto.setUserPassword(encryptpwd);
        userPcMapper.add(userPcDto);
        userRoleMapper.add(userPcDto.getId(), roleId);
    }

    @Override
    public void delete(List<Integer> ids) {
        for (int i = 0; i < ids.size(); i++) {

            userPcMapper.delete(ids.get(i));
            userRoleMapper.deleteByUserId(ids.get(i));
        }
    }

    @Override
    public void update(UserPcDto userPcDto, Integer roleId) {
        //先查询角色是否一致
        Integer integer = userRoleMapper.queryRoleById(userPcDto.getId());
        if (integer != roleId) {
            userRoleMapper.deleteByUserId(userPcDto.getId());
            userRoleMapper.add(userPcDto.getId(),roleId);
        }
        userPcMapper.update(userPcDto);
        //不一致就修改用户角色

    }
}
